package com.example.web.controller;

import com.example.web.entity.Result;
import com.example.web.entity.InteractionRecord;
import com.example.web.entity.Customer;
import com.example.web.service.InteractionRecordService;
import com.example.web.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/interaction-records")
@CrossOrigin(origins = "http://localhost:3000", allowCredentials = "true")
public class InteractionRecordController {

    @Autowired
    private InteractionRecordService interactionRecordService;
    
    @Autowired
    private JwtUtils jwtUtils;

    /**
     * 获取互动记录列表（支持分页和查询）
     */
    @GetMapping
    public Result<Map<String, Object>> getInteractionRecordList(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String interactionType,
            @RequestParam(required = false) Long customerId,
            HttpServletRequest request) {
        try {
            Long creatorId = getCurrentUserId(request);
            if (creatorId == null) {
                return Result.error(401, "未认证");
            }
            
            Map<String, Object> result = interactionRecordService.getInteractionRecordList(
                page, size, interactionType, customerId, creatorId);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error("获取互动记录列表失败: " + e.getMessage());
        }
    }

    /**
     * 根据ID获取互动记录
     */
    @GetMapping("/{id}")
    public Result<InteractionRecord> getInteractionRecordById(@PathVariable Long id, HttpServletRequest request) {
        try {
            Long creatorId = getCurrentUserId(request);
            if (creatorId == null) {
                return Result.error(401, "未认证");
            }
            
            InteractionRecord record = interactionRecordService.findById(id);
            if (record == null) {
                return Result.error(404, "互动记录不存在");
            }
            
            // 检查权限：只能查看自己创建的记录
            if (!record.getCreatorId().equals(creatorId)) {
                return Result.error(403, "无权限访问该互动记录");
            }
            
            return Result.success(record);
        } catch (Exception e) {
            return Result.error("获取互动记录失败: " + e.getMessage());
        }
    }

    /**
     * 创建新的互动记录
     */
    @PostMapping
    public Result<InteractionRecord> createInteractionRecord(@RequestBody InteractionRecord interactionRecord, HttpServletRequest request) {
        try {
            Long creatorId = getCurrentUserId(request);
            if (creatorId == null) {
                return Result.error(401, "未认证");
            }
            
            // 设置创建人
            interactionRecord.setCreatorId(creatorId);
            
            InteractionRecord createdRecord = interactionRecordService.createInteractionRecord(interactionRecord);
            return Result.success("互动记录创建成功", createdRecord);
        } catch (Exception e) {
            return Result.error("创建互动记录失败: " + e.getMessage());
        }
    }

    /**
     * 更新互动记录
     */
    @PutMapping("/{id}")
    public Result<InteractionRecord> updateInteractionRecord(@PathVariable Long id, @RequestBody InteractionRecord interactionRecord, HttpServletRequest request) {
        try {
            Long creatorId = getCurrentUserId(request);
            if (creatorId == null) {
                return Result.error(401, "未认证");
            }
            
            interactionRecord.setId(id);
            interactionRecord.setCreatorId(creatorId);
            
            InteractionRecord updatedRecord = interactionRecordService.updateInteractionRecord(interactionRecord);
            return Result.success("互动记录更新成功", updatedRecord);
        } catch (Exception e) {
            return Result.error("更新互动记录失败: " + e.getMessage());
        }
    }

    /**
     * 删除互动记录
     */
    @DeleteMapping("/{id}")
    public Result<String> deleteInteractionRecord(@PathVariable Long id, HttpServletRequest request) {
        try {
            Long creatorId = getCurrentUserId(request);
            if (creatorId == null) {
                return Result.error(401, "未认证");
            }
            
            // 先检查记录是否存在且属于当前用户
            InteractionRecord record = interactionRecordService.findById(id);
            if (record == null) {
                return Result.error(404, "互动记录不存在");
            }
            if (!record.getCreatorId().equals(creatorId)) {
                return Result.error(403, "无权限删除该互动记录");
            }
            
            boolean deleted = interactionRecordService.deleteInteractionRecord(id);
            if (!deleted) {
                return Result.error(404, "互动记录不存在");
            }
            return Result.success("互动记录删除成功", null);
        } catch (Exception e) {
            return Result.error("删除互动记录失败: " + e.getMessage());
        }
    }

    /**
     * 获取当前用户的客户列表（用于关联下拉选择）
     */
    @GetMapping("/customers")
    public Result<List<Customer>> getCustomersByCreator(HttpServletRequest request) {
        try {
            Long creatorId = getCurrentUserId(request);
            if (creatorId == null) {
                return Result.error(401, "未认证");
            }
            
            List<Customer> customers = interactionRecordService.getCustomersByCreator(creatorId);
            return Result.success(customers);
        } catch (Exception e) {
            return Result.error("获取客户列表失败: " + e.getMessage());
        }
    }

    /**
     * 获取互动类型选项
     */
    @GetMapping("/interaction-types")
    public Result<List<Map<String, String>>> getInteractionTypeOptions(HttpServletRequest request) {
        try {
            if (!isAuthenticated(request)) {
                return Result.error(401, "未认证");
            }
            
            List<Map<String, String>> options = interactionRecordService.getInteractionTypeOptions();
            return Result.success(options);
        } catch (Exception e) {
            return Result.error("获取互动类型选项失败: " + e.getMessage());
        }
    }

    /**
     * 根据客户ID获取互动记录
     */
    @GetMapping("/by-customer/{customerId}")
    public Result<List<InteractionRecord>> getInteractionRecordsByCustomer(@PathVariable Long customerId, HttpServletRequest request) {
        try {
            Long creatorId = getCurrentUserId(request);
            if (creatorId == null) {
                return Result.error(401, "未认证");
            }
            
            List<InteractionRecord> records = interactionRecordService.getInteractionRecordsByCustomer(customerId);
            return Result.success(records);
        } catch (Exception e) {
            return Result.error("获取客户互动记录失败: " + e.getMessage());
        }
    }

    /**
     * 获取当前登录用户ID
     */
    private Long getCurrentUserId(HttpServletRequest request) {
        try {
            String token = extractTokenFromRequest(request);
            if (token == null) {
                return null;
            }
            
            String username = jwtUtils.getUsernameFromToken(token);
            if (!jwtUtils.validateToken(token, username)) {
                return null;
            }
            
            return jwtUtils.getUserIdFromToken(token);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 检查用户是否已认证
     */
    private boolean isAuthenticated(HttpServletRequest request) {
        try {
            String token = extractTokenFromRequest(request);
            if (token == null) {
                return false;
            }
            
            String username = jwtUtils.getUsernameFromToken(token);
            return jwtUtils.validateToken(token, username);
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 从请求中提取Token
     */
    private String extractTokenFromRequest(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        return null;
    }
}